package com.shenyuan.module_mvvm.ui.login;

import androidx.fragment.app.Fragment;

import com.google.android.material.tabs.TabLayoutMediator;
import com.shenyuan.module_mvvm.R;
import com.shenyuan.module_mvvm.api.NewsViewModel;
import com.shenyuan.module_mvvm.bean.NewsTypeBean;
import com.shenyuan.module_mvvm.databinding.AcMvTabBinding;
import com.shenyuan.superapp.base.adapter.BaseTabs2Adapter;
import com.shenyuan.superapp.base.base.mvvm.BaseVMActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ch
 * @date 2022/6/13-14:37
 * desc
 */
public class MVTabActivity extends BaseVMActivity<AcMvTabBinding, NewsViewModel> {

    private List<String> titles = new ArrayList<>();

    private TabLayoutMediator mediator;

    @Override
    protected NewsViewModel createViewModel() {
        return getScopeViewModel(NewsViewModel.class);
    }

    @Override
    protected void initView() {
        viewModel.getNewsType().observe(this, listResult -> {
            if (isSucc(listResult)) {
                if (listResult.getData() != null && listResult.getData().size() > 0) {
                    titles.clear();
                    for (NewsTypeBean bean : listResult.getData()) {
                        titles.add(bean.getTypeName());
                    }
                    BaseTabs2Adapter tabsAdapter = new BaseTabs2Adapter(this, titles) {
                        @Override
                        protected Fragment getFragmentInPosition(int position) {
                            return new MVFragment(listResult.getData().get(position).getTypeId());
                        }
                    };
                    binding.vpMv.setOffscreenPageLimit(5);
                    binding.vpMv.setAdapter(tabsAdapter);
                    mediator = new TabLayoutMediator(binding.tlMv, binding.vpMv, (tab, position) -> {
                        tab.setText(titles.get(position));
                    });
                }
            }
        });
    }

    @Override
    protected void addListener() {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediator != null) {
            mediator.detach();
        }
    }
}
